package com.sptpc.learnspring.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/**
 * 授权
 */
@Slf4j
public class JWTAuthorizationFilter
        extends BasicAuthenticationFilter {
    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(
            HttpServletRequest request, HttpServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        String jwtHeader = JwtUtil.getJwtFromRequest(request);
        // 如果请求中没有token直接放行
        if (jwtHeader==null) {
            chain.doFilter(request, response);
            return;
        }
        // 如果有token，解析token进行认证
        SecurityContextHolder.getContext()
                .setAuthentication(getAuthentication(jwtHeader));
        super.doFilterInternal(request, response, chain);
    }

    // 从token中获得用户名和角色，并生成UsernamePasswordAuthenticationToken进行认证
    private UsernamePasswordAuthenticationToken getAuthentication(String jwtHeader) {
        String username = JwtUtil.getUsernameFromJWT(jwtHeader);
        String role = JwtUtil.getRoleFromJWT(jwtHeader);

        if (username!=null) {
            return new UsernamePasswordAuthenticationToken(
                    username, null,
                    Collections.singleton(new SimpleGrantedAuthority(role))
            );
        }
        return null;
    }
}
